package com.iplant.wms.serviceImpl.dao.wms;

import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.annotation.dao.DBBaseDAO;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.wms.service.po.bill.WMSSalesDeliveryItem;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
@DBBaseDAO(WMSSalesDeliveryItem.class)
public class WMSSalesDeliveryItemDAO extends BaseDAO {


    private static WMSSalesDeliveryItemDAO Instance = null;

    private WMSSalesDeliveryItemDAO() {
        super("");
        this.Init();
    }

    public static WMSSalesDeliveryItemDAO getInstance() {
        if (Instance == null)
            Instance = new WMSSalesDeliveryItemDAO();
        return Instance;
    }


    public void WMS_DeleteSalesDeliveryItem(BMSEmployee wLoginUser, int wSalesDeliveryID, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);

        try {
            if (wSalesDeliveryID <= 0) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }
            Map<String, Object> wDeleteParams = new HashMap<>();
            wDeleteParams.put("SalesDeliveryID", wSalesDeliveryID);
            this.Delete(wDeleteParams, " and ID>0 ");

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("MSS_DeleteSalesDeliveryItem", ex);
        }
    }

    /**
     * 条件查询集合
     */
    public List<WMSSalesDeliveryItem> WMS_SelectSalesDeliveryItemList(BMSEmployee wLoginUser, int wSalesDeliveryID,
                                                 int wMaterialID, Pagination wPagination,
                                                 OutResult<Integer> wErrorCode) {
        Map<String, Object> wParamMap = new HashMap<>();
        wParamMap.put("SalesDeliveryID", wSalesDeliveryID);
        wParamMap.put("MaterialID", wMaterialID);

        return this.SelectPOList(wLoginUser, wParamMap, wPagination, wErrorCode);
    }



    public void WMS_UpdateSalesDeliveryItemFQTY(BMSEmployee wLoginUser, List<Integer> wIDList, OutResult<Integer> wErrorCode){
        wErrorCode.set(0);
        try {
            String wSQLText= StringUtils.Format("update {0} t set t.RealOutFQTY= " +
                            "( select ifnull( sum(t2.FQTY),0) from {1} t2 WHERE t2.StockOperateRecordID>0 and t.ID=t2.SalesDeliveryItemID) where  t.ID IN (2) ",
                    this.getTableName(),this.getTableName("wms_outboundorderitem"),StringUtils.Join(",",wIDList) );

            this.Update(wSQLText,new HashMap<>());
        }catch (Exception e){
            wErrorCode.Result=ExceptionTypes.DBSQL.getValue();
            log.error("WMS_UpdateSalesDeliveryItemFQTY",e);
        }
    }
}
